package com.example.mpgen.controller;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.example.mpgen.entity.DBSource;
import com.example.mpgen.entity.Template;
import com.example.mpgen.repository.DBSourceRepository;
import com.example.mpgen.repository.TemplateRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Collections;
import java.util.Optional;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName MainController.java
 * @Description TODO
 * @createTime 2022年09月27日 14:49:00
 */
@RestController
@RequestMapping("/main")
public class MainController {

    {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @Autowired
    private DBSourceRepository dbSourceRepository;

    @Autowired
    private TemplateRepository templateRepository;
    @PostMapping("/db-source/add")
    public String addDBSource(@RequestBody DBSource dbSource) {
        dbSourceRepository.save(dbSource);
        return "成功!";
    }

    @PostMapping("/db-source/check")
    public String checkDBSource(@RequestBody DBSource dbSource) {
        // 1 mysql 2 ms-sql 3 oracle
        try {
            Connection connection = DriverManager.getConnection(dbSource.getUrl(), dbSource.getUsername(), dbSource.getPassword());
            if (connection == null) {
                return "失败,请检查信息!";
            }
            connection.close();
        } catch (Exception e) {
            String msg =
                    "连接失败！！" +
                    "\nMessage: " + e.getMessage() +
                    "\nCause: " +e.getCause();
            return msg;
        }

        return "成功!";
    }

    @GetMapping("/db-source/get/{id}")
    public DBSource listDBSource(@PathVariable Integer id) {
        Optional<DBSource> dbSource = dbSourceRepository.findById(id);
        return dbSource.get();
    }

    @PostMapping("/db-source/del/{id}")
    public String delDBSource(@PathVariable Integer id) {
        dbSourceRepository.deleteById(id);
        return "成功!";
    }

    @PostMapping("/template/add")
    public String template(@RequestBody Template template) {
        if (!StringUtils.hasLength(template.getName())) {
            template.setName("unknown-" + System.currentTimeMillis() / 1000);
        }
        templateRepository.save(template);
        return "成功!";
    }

    @GetMapping("/template/get/{id}")
    public Template listTemplates(@PathVariable Integer id) {
        Optional<Template> dbSource = templateRepository.findById(id);
        return dbSource.get();
    }

    @PostMapping("/template/del/{id}")
    public String delTemplates(@PathVariable Integer id) {
        templateRepository.deleteById(id);
        return "成功!";
    }

    @PostMapping("/template/gen")
    public String templateGen(@RequestBody Template template) {
        try {
            DBSource dbSource = dbSourceRepository.findById(template.getDsId()).get();
            if (dbSource == null) {
                return "数据源不存在!";
            }
            FastAutoGenerator.create(dbSource.getUrl(), dbSource.getUsername(), dbSource.getPassword())
                    .globalConfig(builder -> {
                        builder.author(template.getAuthor()) // 设置作者
                                .outputDir(template.getOutputDir()); // 指定输出目录
                        if (template.isEnableSwagger()) {
                            builder.enableSwagger(); // 开启 swagger 模式
                        }
                        if (template.isFileOverride()) {
                            builder.fileOverride(); // 覆盖已生成文件
                        }
                    })
                    .packageConfig(builder -> {
                        builder.parent(template.getParent()) // 设置父包名
                                .moduleName(template.getModuleName()) // 设置父包模块名
                                .pathInfo(Collections.singletonMap(OutputFile.xml, template.getOutputDir())); // 设置mapperXml生成路径
                    })
                    .strategyConfig(builder -> {
                        builder.addInclude(template.getIncludes()) // 设置需要生成的表名
                                .addTablePrefix(template.getTablePrefix().split(",")); // 设置过滤表前缀
                    })
                    .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板，默认的是Velocity引擎模板
                    .execute();
        } catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }

        return "成功!";
    }
}
